package com.snails.app.configuration.environment;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Process;

import com.snails.app.SnailsApp;
import com.snails.app.configuration.IConfiguration;
import com.snails.app.configuration.model.SnailsNetwork;
import com.snails.ui.dialog.EnvDialog;

public final class EnvironmentUtil {

    /**
     * 切换 测试环境 or 生产环境，并退出app
     *
     * @param environment true-测试环境，false-生产环境
     */
    public static void onChangedEnvironment(boolean environment) {
        final boolean isTest = SnailsApp.instance().isTest();
        if (isTest != environment) {
            SnailsApp.instance().setTest(environment);
            new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
                @Override
                public void run() {
                    Process.killProcess(Process.myPid());
                }
            }, 1000);
        }
    }

    /**
     * 显示 网络环境 切换对话框
     */
    public static void showEnvDialog(Context ctx) {
        final IConfiguration iConfiguration = SnailsApp.instance().configuration();
        if (iConfiguration != null && iConfiguration.network() != null) {
            final SnailsNetwork network = iConfiguration.network();
            if (!network.isOnline()) {
                final String url = SnailsApp.instance().isTest() ?
                        network.testUrl : network.productUrl();
                final EnvDialog dialog = new EnvDialog.Builder().realUrl(url)
                        .testUrl(network.testUrl)
                        .productUrl(network.productUrl())
                        .listener(new EnvDialog.OnEnvClickListener() {
                            @Override
                            public void onCancel() { }
                            @Override
                            public void onOK(boolean isTest) {
                                onChangedEnvironment(isTest);
                            }
                        }).build(ctx);
                dialog.show();
            }
        }
    }

}
